﻿using DouglasCrockford.JsMin;
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Optimization;

namespace WebApplicationTestJs.Models
{
    public class JsMinify2 : IBundleTransform//JsMinify
    {
        /// <summary>
        /// 是否忽略js代碼錯誤
        /// </summary>
        public bool CodeIgnoreAllErrors { get; set; }
        protected static void GenerateErrorResponse(BundleResponse bundle, IEnumerable<object> errors)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("/* ");
            //stringBuilder.Append(OptimizationResources.MinifyError).Append("\r\n");
            stringBuilder.Append("js代碼有錯").Append("\r\n");
            foreach (object obj in errors)
            {
                stringBuilder.Append(obj.ToString()).Append("\r\n");
            }
            stringBuilder.Append(" */\r\n");
            stringBuilder.Append(bundle.Content);
            bundle.Content = stringBuilder.ToString();
        }
        /// <summary>
        /// 重寫此方法，忽略js報錯，繼續壓縮
        /// </summary>
        /// <param name="context"></param>
        /// <param name="response"></param>
        public virtual void Process(BundleContext context, BundleResponse response)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            if (!context.EnableInstrumentation)
            {
                Minifier minifier = new Minifier();
                string content = minifier.MinifyJavaScript(response.Content, new CodeSettings
                {
                    EvalTreatment = EvalTreatment.MakeImmediateSafe,
                    PreserveImportantComments = false,
                    //自定義，設置忽略錯誤
                    //IgnoreAllErrors = true
                    IgnoreAllErrors= CodeIgnoreAllErrors                   
                });
                if (minifier.ErrorList.Count > 0)
                {               
                    //用其他組件壓縮
                    var minifier3 = new JsMinifier();
                    string content2 = minifier3.Minify(response.Content);
                    response.Content = content2;
                }
                else
                {
                    response.Content = content;
                }
            }
            response.ContentType = "text/javascript";// JsMinify.JsContentType;
        }
    }
}